﻿<%@page import="com.cchr.acms.util.HtmlComponentUtil.SelectOption"%>
<%@page import="java.util.List"%>
<%@page import="com.cchr.acms.util.HtmlComponentUtil"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%>
<link href="<%=request.getContextPath()%>/assets/stylesheets/jquery.dataTables.css" rel="stylesheet" />
<style> 
	.dataTables_wrapper .dataTables_paginate .paginate_button{
		padding: 0px
	}
    .black_overlay{ 
        z-index:999; 
        display:none; 
        position:fixed;
        width:100%;
        height:100%;
        left:0;top:0; 
        background-color:Black;
        opacity: 0.5;
    } 
    .white_content { 
        display: none; 
        position: absolute; 
        top: 10%; 
        left: 15%; 
        width: 60%; 
        height: 80%; 
        padding: 20px; 
        border: 1px solid blue; 
        background-color: white; 
        z-index:1002; 
        overflow: auto; 
    } 

	<!--
	#jq-datatables-example_wrapper .table-header{
		display: none;
	}
	-->
</style>
	<!--show list-->
	<div class="row">
			<div class="col-sm-12">
				<div id="searchAreaDiv1" class="panel">
					 <!--search conditions-->
					<div class="row">
						<div class="col-sm-12">
						<form class="form-horizontal " role="form" id="userList" >
							<div id="searchAreaDiv" class="panel-body" style="padding:20px">
								<div class="row">
									<div class="col-sm-4">
										<div class="form-group">
											<label  class="col-sm-5 control-label">Name:</label>
											<div class="col-sm-7">
												<input type="text" class="form-control" name="user.userName" id="s_userName">
											</div> 
										</div>
									</div>						
									<div class="col-sm-4">
										<div class="form-group">
											<label  class="col-sm-5 control-label">User Email:</label>
											<div class="col-sm-7">
												<input type="text" class="form-control" name="user.email" id="s_email">
											</div> 
										</div>
									</div>
									<div class="col-sm-4 ">
										<a class="btn btn-primary" id="searchBtn" style="border-radius:0px; width:110px">Search</a>&nbsp;&nbsp;
									</div>
								</div>
								
							</div>

							</div>
						</form>
						</div>

					</div>
					
					<div class="row">
						<div class="col-sm-12">
<!-- 							    <div class="col-sm-4" style="padding-left:0px;padding-bottom:10px">
									<a class="btn btn-primary" id="addBtn" style="border-radius:7px;width:110px" onClick="addUser();return false;">&nbsp;Add&nbsp;</a>
									
									<a class="btn btn-primary" id="addBtn" style="border-radius:7px;width:110px" onClick="editUser();return false;">&nbsp;Edit&nbsp;</a>
									
									<a class="btn btn-primary" id="addBtn" style="border-radius:7px;width:110px" onClick="deleteUser();return false;">Remove</a>
								</div> -->
								<div class="table table-primary">
									<table cellpadding="0" cellspacing="0" border="0" class="table table-bordered display" style="width:100%" id="jq-datatables-example">
										<thead>
											<tr>
											    <th>Email</th>
												<th>Name</th>
												<th>User Type</th>
												<th>Status</th>
												<!-- th>First Name</th>
												<th>Middle Name</th>
												<th>Last Name</th>
												<th>Telephone</th>
												<th>Last Updated By</th>
												<th>Operation</th -->
											</tr>
										</thead>
									</table>
								</div>
						</div>
					</div>
				</div><!-- / #panel -->
		</div><!-- / #row -->
		
        <!-- Modal -->
				<div id="myModal" class="modal fade">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
								<h4 class="modal-title" id="myModalLabel">User Management</h4>
							</div>
							<div class="modal-body">
								<input type="hidden" name="userId" id="userId">
								<div class="row">
									<div class="col-sm-6">
										<div class="form-group no-margin-hr">
											<label class="control-label">Type</label>
											<select id="type" name="type" data-placeholder="Choose type..." >
												<option value=""></option>
											    <option value="3">Chapter Staff</option>
												<option value="2">CCHR Officer</option>
												<option value="1">Admin</option>
											</select>
										</div>
									</div>
									<div class="col-sm-6">
										<div class="form-group no-margin-hr">
											<label class="control-label">Name</label>
											<input class="form-control" type="text" placeholder="Name" name="userName" id="userName">
										</div>
									</div>
									<input type="hidden" name="status" id="status" value="2">
								</div>

						        <div class="row">
									<div class="col-sm-6">
										<div class="form-group no-margin-hr">
											<label class="control-label">Email</label>
											<input class="form-control" type="text" placeholder="Email" name="email" id="email">
										</div>
									</div>
									<div class="col-sm-6">
										<div class="form-group no-margin-hr">
											<label class="control-label">Password</label>
											<input class="form-control" type="password" placeholder="Password" name="password" id="password">
										</div>
									</div>
								</div>
								<div class="row" id="chapterInfo">
									<div class="col-sm-6">
										<div class="form-group no-margin-hr">
											<label class="control-label">Country</label>
											<%= HtmlComponentUtil.getSelect("chCountry", "chCountry", (List<SelectOption>)request.getAttribute("countryDatas"), "", "Choose Country...") %>
										</div>
									</div>
									<div class="col-sm-6">
										<div class="form-group no-margin-hr">
											<label class="control-label">Chapter Name</label>
											<select id="chChapter" name="chChapter" data-placeholder="Choose Chapter..." ><option value=""></option>
							                </select>
										</div>
									</div>
								</div>
							</div> 
							<div class="modal-footer">
								<button type="button" class="btn btn-default" style="border-radius:0px;width:110px;" onClick="closeDiv();return false;">Cancel</button>
								<button type="button" class="btn btn-primary" id="addBtn" style="border-radius:0px; width:110px;" onClick="saveUser();return false;">Save</button>
							</div>
						</div> <!-- / .modal-content -->
					</div> <!-- / .modal-dialog -->
				</div> <!-- /.modal -->
				<!-- / Modal -->
				
				<div id="uidemo-modals-alerts-success" class="modal modal-alert modal-success fade">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<i class="fa fa-check-circle"></i>
							</div>
							<div class="modal-title"  id="successMsg"></div>
							<div class="modal-footer">
								<button type="button" class="btn btn-success submitConfim" style="border-radius:0px;width:110px;" onClick="window.location.reload();">OK</button>
							</div>
						</div> <!-- / .modal-content -->
					</div> <!-- / .modal-dialog -->
				</div>
				
				<div id="uidemo-modals-alerts-warning" class="modal modal-alert modal-warning fade">
				<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<i class="fa fa-warning"></i>
							</div>
							<div class="modal-title" id="warningMsg"></div>
							<div class="modal-footer">
								<button type="button" class="btn btn-warning submitConfim" style="border-radius:0px; width:110px;" onClick="$('#uidemo-modals-alerts-warning').modal('hide');">OK</button>
							</div>
						</div> <!-- / .modal-content -->
					</div> <!-- / .modal-dialog -->
				</div>
	
	           <div id="uidemo-modals-alerts-confirm" class="modal modal-alert modal-success fade">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<i class="fa fa-check-circle"></i>
							</div>
							<div class="modal-title">Are you sure to delete the user?</div>
							<div class="modal-footer">
								<button type="button" id="confirmButton" class="btn btn-success submitConfim" style="border-radius:0px;width:110px;">Yes</button>
								<button type="button" class="btn btn-default" data-dismiss="modal" style="border-radius:0px; width:110px;" onClick="$('#uidemo-modals-alerts-confirm').modal('hide');">No</button>
							</div>
						</div> <!-- / .modal-content -->
					</div> <!-- / .modal-dialog -->
				</div>
				
	<script>
		function resetForm(){
			$("#userId").val("");
		    $("#userName").val("");
		    $("#password").val("");
		    $("#type").val("");
		    $("#email").val("");
		    $("#status").val("");
		    $('#chCountry').select2().val(null).trigger("change");
            $('#chChapter').select2().val(null).trigger("change");
            $('#chChapter option:gt(0)').remove();
            $('#type').select2().val(null).trigger("change");
		}
		
	    function addUser(){
	    	resetForm();
	    	$('#chapterInfo').hide();
	    	$("#status").val('2');
	    	$('#myModal').modal('show')
	    }
	    
	    function editUser(){
	    	resetForm();
	    	var r = $('#jq-datatables-example').DataTable().row('.selected');
	        if(r && r.data() && r.data().id && r.data().id != null){
		    	$.ajax( {  
		    		  url:'<%=request.getContextPath()%>/user/detail/'+r.data().id, 
		    		  data:{	    		       
		    		  },  
		    		  type:'post',  
		    		  cache:false,  
		    		  dataType:'json',  
		    		  success:function(data) {  
			    		          if(data.success =="Y" ){  
			    		        	    $('#chCountry').select2().val(data.chCountry).trigger("change");
				    		        	$("#userId").val(data.userId);
				    		  		    $("#userName").val(data.userName);
				    		  		    $("#password").val('');
				    		  		    $("#email").val(data.email);
				    		  		    $("#status").val(data.status);
				    		  		    $("#type").select2().val(data.type).trigger("change");
				    		  		    if(data.type==3){
				    		  		    	$('#chapterInfo').show();
				    		  		    }else{
				    		  		    	$('#chapterInfo').hide();
				    		  		    }

							             $.ajax({
							                 type: "post",
							                 contentType: "application/x-www-form-urlencoded",
							                 url: "${pageContext.request.contextPath}/user/GetChapters",
							                 data: {country:data.chCountry},
							                 success: function (result) {
							                     var strocity = '';
							                     for (var i = 0; i < result.length; i++) {
							                    	 if(result[i].chapter==data.chapter){
							                    		 strocity += '<option value=' + result[i].id + ' selected="selected">';
							                    	 }else{
							                    		 strocity += '<option value=' + result[i].id + '>';
							                    	 }
							                         strocity += result[i].chapter;
							                         strocity += '</option>';
							                     }
							                     $('#chChapter').append(strocity);
							                     $('#chChapter').select2();
							                 }
							             });
				    		  		  	$('#myModal').modal('show');

			    		          }else{  
			    		                $('#warningMsg').html(data.msg);
			    			        	$('#uidemo-modals-alerts-warning').modal('show');
			    		          }
		    		          },  
		    		          error : function() {  
		    		             alert("Error occurred！");  
		    		          }  
		        });
	        }else{
	        	$('#warningMsg').html('No record selected!');
	        	$('#uidemo-modals-alerts-warning').modal('show');
	        }
	    }
	    
	    function closeDiv(){
	    	resetForm();
	    	$('#myModal').modal('hide')
	    }
	    
	    function saveUser(){
	    	$.ajax( {  
	    		   url:'<%=request.getContextPath()%>/user/save', 
	    		   data:{
	    			   userId:$("#userId").val(),
	    		       userName:$("#userName").val(),
	    		       password:$("#password").val(),
	    		       type:$("#type").val(),
	    		       email:$("#email").val(),
	    		       status:$("#status").val(),
	    		       country:$('#chCountry').val(),
	    		       state:$('#chStates').val(),
	    		       chapterId:$("#chChapter").val()
	    		  },  
	    		  type:'post',  
	    		  cache:false,  
	    		  dataType:'json',  
	    		  success:function(data) {  
		    		          if(data.success =="Y" ){  
		    		        	  closeDiv();
		    		        	  $('#successMsg').html('User info saved successfully!');
		    		        	  $('#uidemo-modals-alerts-success').modal('show');
		    		          }else{ 
		    		        	  $('#warningMsg').html(data.msg);
		    		        	  $('#uidemo-modals-alerts-warning').modal('show');
		    		          }  
	    		          },  
	    		          error : function() {  
	    		        	  $('#warningMsg').html('Error occurred!');
	    		        	  $('#uidemo-modals-alerts-warning').modal('show');
	    		          }  
	         });
	    }
	    
	    function deleteUser(){
	    	var r = $('#jq-datatables-example').DataTable().row('.selected');
	        if(r && r.data() && r.data().id && r.data().id != null){
	        	$('#uidemo-modals-alerts-confirm').modal('show');
	        }else{
	        	$('#warningMsg').html('No record selected!');
	        	$('#uidemo-modals-alerts-warning').modal('show');
	        }
	    	
	    }
	    
		init.push(function () {	
			
			$("select:not(.unRender)").select2({
			    allowClear: true
			});
			
			$('#chapterInfo').hide();
			
			$('#type').on("click", function () {
		    	 $('#chCountry').select2().val(null).trigger("change");
	             $('#chChapter').select2().val(null).trigger("change");
	             $('#chChapter option:gt(0)').remove();
	             if($('#type').val()==2||$('#type').val()==1){
	            	 $('#chapterInfo').hide();
	             }else{
	            	 $('#chapterInfo').show();
	             }
	      	});
			
			var operationButtonInit = function(data, type, full) {
				var comp = '<td><div class="btn-group btn-group-sm">' + 
								'<a target="_blank" class="btn btn-primary" type="button" href=\'${pageContext.request.contextPath}/user/detail/'+ full.id +'\'>View</a>' +
								'<button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" type="button"><i class="fa fa-caret-down"></i></button>' +
								'<ul class="dropdown-menu">' +
									'<li><a target="_blank" type="button" href="#" onClick="editUser('+ full.id +');return false;">Edit</a></li>' +
									'<li><a target="_blank" type="button" href="#" onClick="deleteUser('+ full.id +');return false;">Delete</a></li>' +
								'</ul>' +
							'</div></td>';
				return comp;
			};
			
			var statusInit = function(data, type, full) {
				var comp = '<div class="' + full.status + '">' + (full.status=='1'?'New':(full.status=='2'?'Normal':(full.status=='3'?'Disable':'Deleted')))
							'</div>';
				return comp;
			};
			
			var typeInit = function(data, type, full) {
				var str = '';
				if(full.type == '1')
				{
					str = 'Admin';
				}
				else if(full.type == '2')
				{
					str = 'CCHR Officer';
				}else if(full.type == '3')
				{
					str = 'Chapter Staff';
				}
				var comp = '<div class="' + full.type + '">' + str
							'</div>';
				return comp;
			};
			
			window.dataTable = $('#jq-datatables-example').dataTable( {
				'sPaginationType' : 'full_numbers',
				'bProcessing' : true,
				'bServerSide' : true,
				'bDeferRender' : true,
				"sServerMethod" : "POST",
				"bLengthChange": false, //改变每页显示数据数量
				"bSort": false, //排序功能
				"bFilter": false,
				"iDisplayLength" : ${user.pageSize}, 
				"ajax": {
				    "url": '${pageContext.request.contextPath}/user/getUserListJson',
				    "data": function ( d ) {
				        d.userName = $('#s_userName').val();
				        d.email = $('#s_email').val();
					}
				},
				'aoColumnDefs' : [
				                  {aTargets : [ '_all' ], sDefaultContent : '&nbsp;'},
				                  {aTargets : [ 0 ], mData : 'email'},
				                  {aTargets : [ 1 ], mData : 'userName'},
				                  {aTargets : [ 2 ], mRender : typeInit},
				                  {aTargets : [ 3 ], mRender : statusInit}
				                  ],
				 'fnInitComplete' : function(){
					 $('#jq-datatables-example tbody').on('click', 'tr', function () {
				        if ($(this).hasClass('selected') ) {
				            $(this).removeClass('selected');
				        }
				        else {
				        	$('#jq-datatables-example').DataTable().$('tr.selected').removeClass('selected');
				            $(this).addClass('selected');
				        }
				    });
				 }
			}); 
	      
	      $('#searchBtn').click(function(){
				var settings = window.dataTable.fnSettings();
				settings._iDisplayStart = 0;
				window.dataTable.fnDraw();
	      });
	      
			$("#searchIcon").click(function(){  
				if($("#searchAreaDiv").is(":hidden")){
					$("#searchAreaDiv1").show();
					$("#searchAreaDiv").show();
					}else{
						$("#searchAreaDiv1").hide();
						$("#searchAreaDiv").hide();
					}
					
		      }); 
			
			$("document").ready(function(){
				$("#searchAreaDiv1").hide();
				$("#searchAreaDiv").hide();
				});
		
	      $('#confirmButton').click(function(){
	    	  $('#uidemo-modals-alerts-confirm').modal('hide');
	    	  var r = $('#jq-datatables-example').DataTable().row('.selected');
	    	  $.ajax( {  
	      		  url:'<%=request.getContextPath()%>/user/delete', 
	      		  data:{
	      			   userId:r.data().id	    		       
	      		  },  
	      		  type:'post',  
	      		  cache:false,  
	      		  dataType:'json',  
	      		  success:function(data) {  
	    	    		          if(data.success =="Y" ){
	    	    		               $('#successMsg').html('User deleted successfully!');
	    		    		           $('#uidemo-modals-alerts-success').modal('show');
	    	    		          }else{  
	    	    		        	  $('#warningMsg').html(data.msg);
	    	    		        	  $('#uidemo-modals-alerts-warning').modal('show');
	    	    		          }  
	      		          },  
	      		          error : function() {  
	      		        	  $('#warningMsg').html('Error occurred!');
	      			        	$('#uidemo-modals-alerts-warning').modal('show');
	      		          }  
	              });
	      });
		  
	     $('#chCountry').on("click", function () {  
             $('#chChapter').select2().val(null).trigger("change");
             $('#chChapter option:gt(0)').remove();
             $.ajax({
                 type: "post",
                 contentType: "application/x-www-form-urlencoded",
                 url: "${pageContext.request.contextPath}/user/GetChapters",
                 data: {country:$('#chCountry').val()},
                 success: function (result) {
                     var strocity = '';
                     for (var i = 0; i < result.length; i++) {
                         strocity += '<option value=' + result[i].id + '>';
                         strocity += result[i].chapter;
                         strocity += '</option>';
                     }
                     $('#chChapter').append(strocity);
                 }
             });
      	});
	      	
    });
</script>
